<?php

namespace App\Http\Controllers\Common;

use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Config;
use Exception;
use Request;
use Response;

class FileController extends Controller
{
    const ALLOW_EXTENSIONS = ['gif', 'jpeg', 'jpg', 'png', 'mp4', 'mpg', 'mpeg', 'avi', 'wav', 'mp3', 'amr', 'caf', 'aac', 'apk', 'pdf', 'doc', 'docx', 'zip', 'rar', 'gzip'];

    /**
     * 配合jQuery plugins fileinput 删除btn使用
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete()
    {
        return Response::json([
            'code' => 200,
            'message' => 'success'
        ]);
    }

    /**
     * 上传文件
     */
    public function upload()
    {
        $file = current(Request::allFiles());
        $isfullPath = Request::get('is_full_path');
        $url = '';
        if (empty($file)) {
            return Response::json([
                'code' => 404,
                'message' => '请选择文件',
            ]);
        }
        if (is_array($file)) {
            $file = current($file);
        }
        try {
            if (Request::hasFile('upload')){ //CKEditor

                $url = $this->uploadImage($file, $isfullPath);

                if (Request::has('CKEditorFuncNum')) {
                    $funcNum = $_GET['CKEditorFuncNum'];
                    echo "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction($funcNum, '$url');</script>";
                } else {
                    return Response::json([
                        'uploaded' => 1,
                        'fileName' => basename($url),
                        'url' => $url,
                    ]);
                }
            } else {
                if (Request::get('type') == 'video') {
                    $url = $this->uploadVideo($file);
                } else if (Request::get('type') == 'audio') {
                    $url = $this->uploadAudio($file);
                } else if (Request::get('type') == 'image') {
                    $url = $this->uploadImage($file, $isfullPath);
                } else if (Request::get('type') == 'other') {
                    $url = $this->uploadOther($file);
                }

                if(is_string($url)){
                    return Response::json([
                        'code' => 200,
                        'message' => 'success',
                        'data' => $url,
                    ]);
                }else{
                    return $url;
                }
            }
        } catch (Exception $e) {
            return Response::json([
                'code' => 500,
                'message' => '上传失败，message：' . $e->getMessage(),
            ]);
        }
    }

    public function uploadImage($file, $isfullPath)
    {
        $extension = strtolower($file->getClientOriginalExtension());
        if (!in_array($extension, static::ALLOW_EXTENSIONS)){
            return Response::json([
                'code' => 500,
                'message' => 'failure',
                'data' => 'This type of file is not allowed to upload',
            ], 500);
        }

        $year = Carbon::now()->format('Y');
        $month = Carbon::now()->format('m');
        $day = Carbon::now()->format('d');
        $time = Carbon::now()->format('YmdHis');

        $relativePath = Config::get('site.upload.image_path') . '/' . $year . '/' . $month . $day . '/';
        $uploadPath = public_path() . $relativePath;
        $filename = $time . mt_rand(100, 999) . '.' . $extension;
        $targetFile = $uploadPath . $filename;

        $file->move($uploadPath, $targetFile);

        //同步文件到云端
        //sync2qiniu('images',$relativePath . $filename, $targetFile);

        $url = Config::get('site.upload.url_prefix') . $relativePath . $filename;

        if($isfullPath && $isfullPath == 1) {
            $url = get_cdn_url($url);
        }
        return $url;
    }

    public function uploadVideo($file)
    {
        $extension = strtolower($file->getClientOriginalExtension());
        if (!in_array($extension, static::ALLOW_EXTENSIONS)){
            return Response::json([
                'code' => 500,
                'message' => 'failure',
                'data' => 'This type of file is not allowed to upload',
            ], 500);
        }

        $year = Carbon::now()->format('Y');
        $month = Carbon::now()->format('m');
        $day = Carbon::now()->format('d');
        $time = Carbon::now()->format('YmdHis');

        $relativePath = Config::get('site.upload.video_path') . '/' . $year . '/' . $month . $day . '/';
        $uploadPath = public_path() . $relativePath;
        $filename = $time . mt_rand(100, 999) . '.' . $extension;
        $targetFile = $uploadPath . $filename;

        $file->move($uploadPath, $targetFile);

        //同步文件到云端
        //sync2qiniu('videos',$relativePath . $filename, $targetFile);

        $url = Config::get('site.upload.url_prefix') . $relativePath . $filename;

        return $url;
    }

    public function uploadAudio($file)
    {
        $extension = strtolower($file->getClientOriginalExtension());
        if (!in_array($extension, static::ALLOW_EXTENSIONS)){
            return Response::json([
                'code' => 500,
                'message' => 'failure',
                'data' => 'This type of file is not allowed to upload',
            ], 500);
        }

        $year = Carbon::now()->format('Y');
        $month = Carbon::now()->format('m');
        $day = Carbon::now()->format('d');
        $time = Carbon::now()->format('YmdHis');

        $relativePath = Config::get('site.upload.audio_path') . '/' . $year . '/' . $month . $day . '/';
        $uploadPath = public_path() . $relativePath;
        $filename = $time . mt_rand(100, 999) . '.' . $extension;
        $targetFile = $uploadPath . $filename;

        $file->move($uploadPath, $targetFile);

        //同步文件到云端
        //sync2qiniu('audios',$relativePath . $filename, $targetFile);

        $url = Config::get('site.upload.url_prefix') . $relativePath . $filename;

        return $url;
    }

    public function uploadOther($file)
    {
        $extension = strtolower($file->getClientOriginalExtension());
        if (!in_array($extension, static::ALLOW_EXTENSIONS)){
            return Response::json([
                'code' => 500,
                'message' => 'failure',
                'data' => 'This type of file is not allowed to upload',
            ], 500);
        }

        $year = Carbon::now()->format('Y');
        $month = Carbon::now()->format('m');
        $day = Carbon::now()->format('d');
        $time = Carbon::now()->format('YmdHis');

        $relativePath = Config::get('site.upload.other_path') . '/' . $year . '/' . $month . $day . '/';
        $uploadPath = public_path() . $relativePath;
        $filename = $time . mt_rand(100, 999) . '.' . $extension;
        $targetFile = $uploadPath . $filename;

        $file->move($uploadPath, $targetFile);

        //同步文件到云端
        //sync2qiniu('others',$relativePath . $filename, $targetFile);

        $url = Config::get('site.upload.url_prefix') . $relativePath . $filename;

        return $url;
    }

}
